<template>
  <div class="ad-player"
       :style="{
          width:playerWidth,
          height:playerHeight
       }"
  >
    <img v-if="uri" class="ad-player-cover" :style="{
          width:playerWidth,
          height:playerHeight
         }" :src="bg">
    <img v-if="image" class="ad-player-cover"
         :style="{
          width:playerWidth,
          height:playerHeight
         }"
         :src="image"/>
    <es-player-manager
        ref="playerManager"
        :smallWindowWidth="playerWidth"
        :smallWindowHeight="playerHeight"
        :initPlayerWindowType="1"
        :playMediaAuto="false"
        :playerList="playerListRef"
        @onPlayerMediaListInitialized="onPlayerMediaListInitialized"
        @onPlayerCompleted="onPlayerCompleted"
        @onPlayerStopped="onPlayerStopped"
        @onPlayerPlaying="onPlayerPlaying"
        @onPlayerError="onPlayerError"
        @onPlayerProgressChanged="onPlayerProgressChanged"
    />
    <qt-view class="ad-player-mask"
             ref="adPlayerMaskRef"
             :style="{
          backgroundImage:mask,
          backgroundPosition:'center',
          backgroundSize:'cover',
          width:playerWidth,
          height:playerHeight

             }"
             :focusable="true"
             :enableFocusBorder="true"
             :clipChildren="false"
             @click="adPlayerClick"
    >
    </qt-view>
  </div>
</template>

<script lang="ts">
import {defineComponent, markRaw, ref, watch} from "vue";
import { ESMediaSource, ESMediaSourceList, ESPlayerPlayMode} from "@extscreen/es3-player";
import {ESVideoPlayer} from "@extscreen/es3-video-player";
import {ESIPlayerManager, ESMediaItem, ESMediaItemList,ESPlayerManager} from "@extscreen/es3-player-manager";
import {useESLog} from "@extscreen/es3-core";

export default defineComponent({
  name: 'ArkVideoPlayer',
  emits:['adPlayerClick'],
  components:{
    'es-player-manager':ESPlayerManager
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    image:{
      type:String,
    },
    uri:{
      type:String,
      required:true
    },
    playerWidth:{
      type:Number,
      required:true
    },
    playerHeight:{
      type:Number,
      required:true
    },
    bg:{
      type:String,
      default:'none'
    },
    mask:{
      type:String,
      default:'none'
    }
  },
  setup(props,{emit}) {
    const TAG = 'upstair';
    const log = useESLog();
    const playerManager = ref<ESIPlayerManager>();
    const playerList = [markRaw(ESVideoPlayer)];
    const playerListRef = ref(playerList);
    const isPlaying = ref(false);
    const adPlayerMaskRef=ref()
    const playerProgress=ref(0)
    const isStopPlayer=ref(false)
    let progressTimer:NodeJS.Timeout|null=null
    watch(() => [playerManager.value, props.visible,props.uri], ([newPlayerManager, newShowAd,newUri]) => {
      log.d(TAG,'playerManager:' + !!playerManager.value + ' showAd:' + props.visible+' uri:'+newUri);
      if (newPlayerManager && newShowAd&&newUri) {
        initAd(props.uri);
      }
    });
    watch(()=>isPlaying.value,(newVal,oldVal)=>{
      if (newVal){
        startProgressTimer()
      }else{
        stopProgressTimer()
      }
    })
    function initAd(uri:string) {
      console.log('initAd');
      let mediaSource: ESMediaSource = {
        uri: uri
      };
      let mediaSourceList: ESMediaSourceList = {
        index: 0,
        list: [mediaSource]
      };
      let mediaItem: ESMediaItem = {
        mediaSourceList: mediaSourceList,
      };
      let playList: ESMediaItemList = {
        index: 0,
        list: [mediaItem]
      };
      playerManager.value?.initialize();
      playerManager.value?.setPlayMediaListMode(ESPlayerPlayMode.ES_PLAYER_PLAY_MODE_LOOP);
      playerManager.value?.playMediaList(playList);
    }
    function stopProgressTimer(){
      if (progressTimer){
        log.d(TAG,'adPlayer stopProgressTimer')
        clearInterval(progressTimer)
        progressTimer=null
      }
    }
    //启动定时器，记录当前进度
    function startProgressTimer(){
      stopProgressTimer()
      log.d(TAG,'adPlayer startProgressTimer')
      progressTimer=setInterval(()=>{
        playerManager.value?.getCurrentPosition()
      },500)
    }
    //播放完成后，显示封面
    function onPlayerCompleted(){
      log.d(TAG,'onPlayerCompleted')
      isPlaying.value=false
    }
    function onPlayerStopped(){
      log.d(TAG,'onPlayerStopped')
      isPlaying.value=false
    }
    function onPlayerPlaying(){
      log.d(TAG,'onPlayerPlaying')
      isPlaying.value=true
    }
    function onPlayerError(){
      console.log('onPlayerError')
      playerManager.value?.stop()
      isPlaying.value=false
    }
    function onPlayerProgressChanged(progress:number){
      playerProgress.value=progress
    }
    function onPlayerMediaListInitialized(){
      console.log('onPlayerMediaListInitialized')
      playerProgress.value=0
      playerManager.value?.playMediaByIndex(0)
    }
    function adPlayerClick(){
      emit('adPlayerClick')
    }
    //页面生命周期控制
    function onESResume(){
      //播放器控制
      log.d(TAG,'adPlayer onESResume isPlaying:'+isPlaying.value)
      if (!isPlaying.value&&props.visible&&props.uri){
        log.d(TAG,'adPlayer resume')
        if (isStopPlayer.value){
          playerManager.value?.resume()
        }else{
          playerManager.value?.start(playerProgress.value)
        }
      }
    }
    function onESPause(isStop:boolean=true){
      //播放器控制
      if (isPlaying.value&&props.visible&&props.uri){
        //提前显示封面，防止黑屏
        isPlaying.value=false
        isStopPlayer.value=isStop
        if (isStop){
          playerManager.value?.stop()
        }else{
          playerManager.value?.pause()
        }
      }
    }
    function onESDestroy(){
      console.log(TAG,'adPlayer onESDestroy')
      stopProgressTimer()
      playerManager.value?.stop()
      playerManager.value?.release()
    }
    function requestFocus(){
      adPlayerMaskRef.value?.requestFocus()
    }
    return {
      playerListRef,
      playerManager,
      onPlayerMediaListInitialized,
      onPlayerCompleted,
      onPlayerStopped,
      onPlayerPlaying,
      adPlayerClick,
      isPlaying,
      onESResume,
      onESPause,
      onESDestroy,
      requestFocus,
      adPlayerMaskRef,
      onPlayerError,
      onPlayerProgressChanged,
    };
  }
});
</script>

<style scoped>
.ad-player-mask{
  position: absolute;
  focus-border-radius:25px;
}
.ad-player-cover{
  position: absolute;
  border-radius: 25px;
}
.ad-player{
  position: absolute;
  top: 0;
  background-color: transparent;
}

</style>
